package workqueues;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Worker {
    private final static String TASK_QUEUE_NAME = "task_queue";

    public static void main(String[] args) {
        try {
            //创建连接工厂
            ConnectionFactory factory = new ConnectionFactory();
            //设置rabbitmq地址
            factory.setHost("127.0.0.1");
            factory.setUsername("admin");
            factory.setPassword("admin");
            //建立连接
            Connection connection = factory.newConnection();
            //获得信道
            Channel channel = connection.createChannel();
            //声明队列
            channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
            channel.basicQos(1); //设置每次只分发一条消息给消费者，默认是0，表示不限制;
            //接收消息
            channel.basicConsume(TASK_QUEUE_NAME, false, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String message = new String(body, "UTF-8");
                    System.out.println(" [x] 收到了消息：'" + message + "'");
                    doWork(message);
                    System.out.println(" [x] 消息处理完成");
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

    private static void doWork(String task) {
        char[] chars = task.toCharArray();
        for (char c : chars) {
            if (c == '.') {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
}
